<template>
  <div class="profile-container">
    <el-row :gutter="20" style="display: flex; align-items: stretch; flex: 1;">
      <el-col :span="12" style="height: 100%;">
        <!-- 个人信息卡片 -->
        <el-card class="profile-card" style="display: flex; flex-direction: column; height: 100%;">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          <div class="card-content" style="flex: 1; overflow-y: auto;">
            <div class="avatar-container">
              <el-avatar :size="100" :src="userInfo.avatar" />
            </div>
            <div class="info-list">
              
              <div class="info-item">
                <span class="label"><b>用户名：</b></span>
                <span class="value">{{ userInfo.username }}</span>
              </div>
              <div class="info-item">
                <span class="label"><b>昵称</b></span>
                <span class="value">{{ userInfo.nickname }}</span>
              </div>
              <div class="info-item">
                <span class="label"><b>性别：</b></span>
                <span class="value">{{
                  userInfo.gender == 1 ? "男" : "女"
                }}</span>
              </div>
              <div class="info-item">
                <span class="label"><b>联系电话：</b></span>
                <span class="value">{{ userInfo.phone }}</span>
              </div>
              <div class="info-item">
                <span class="label"><b>电子邮箱：</b></span>
                <span class="value">{{ userInfo.email }}</span>
              </div>
            </div>
          </div>
          
        </el-card>
      </el-col>

      <el-col :span="12" style="height: 100%;">
        <!-- 基本信息编辑 -->
        <el-card class="edit-card" style="display: flex; flex-direction: column; height: 100%;">
          <template #header>
            <div class="card-header">
              <span>修改信息</span>
            </div>
          </template>
          <el-form
            ref="basicFormRef"
            :model="basicForm"
            :rules="basicRules"
            label-width="100px"
            style="flex: 1; margin-bottom: 20px; overflow-y: auto;"
          >
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
              >
                <img
                  v-if="basicForm.avatar"
                  :src="basicForm.avatar"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="用户名" prop="username">
              <el-input v-model="basicForm.username" disabled />
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="basicForm.nickname" />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-select
                v-model="basicForm.gender"
                placeholder="请选择性别"
                class="dialog-input"
              >
                <el-option
                  v-for="item in genderOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="basicForm.phone" />
            </el-form-item>
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="basicForm.email" />
            </el-form-item>
          </el-form>
          <div class="button-container" style="display: flex; justify-content: space-between; padding: 0 20px;">
            <el-button type="warning" @click="handleReset">重置</el-button>
            <el-button type="primary" @click="handleSaveBasic">保存修改</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import axios from "axios";
import { updateUser } from "@/request/request";

// 用户信息
const userInfo = ref(JSON.parse(localStorage.getItem("userInfo")));

// 基本信息表单
const basicFormRef = ref(null);
const basicForm = reactive({
  avatar: userInfo.value.avatar,
  username: userInfo.value.username,
  nickname: userInfo.value.nickname,
  gender: userInfo.value.gender,
  phone: userInfo.value.phone,
  email: userInfo.value.email,
});

// 性别选项
const genderOptions = [
  { label: "男", value: 1 },
  { label: "女", value: 0 },
];

// 表单验证规则
const basicRules = {
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  gender: [{ required: true, message: "请选择性别", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入电子邮箱", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: "请输入正确的电子邮箱",
      trigger: "blur",
    },
  ],
};

// 头像上传相关方法
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("上传头像图片只能是 JPG/PNG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
  }
  return isJPG && isLt2M;
};

const handleAvatarUpload = async (options) => {
  const formData = new FormData();
  formData.append("file", options.file);
  const url =
    "http://localhost:8090/user/avatar/upload?Token=" +
    localStorage.getItem("token");
  const res = await axios.post(url, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
  if (res.data.code == 200) {
    ElMessage.success("上传成功");
    basicForm.avatar = res.data.data;
  } else {
    ElMessage.error("上传失败");
  }
};

// 保存基本信息
const handleSaveBasic = async () => {
  if (!basicFormRef.value) return;

  try {
    await basicFormRef.value.validate();
    const res = await updateUser(userInfo.value.id, basicForm);
    console.log(res);
    if (res.code == 200) {
      ElMessage.success("保存成功");
      userInfo.value = res.data;
      localStorage.setItem("userInfo", JSON.stringify(userInfo.value));
      window.location.reload();
    } else {
      ElMessage.error("保存失败");
    }
  } catch (error) {
    console.error("表单验证失败：", error);
  }
};

// 重置基本信息
const handleReset = () => {
  basicForm.avatar = null;
  basicForm.username = userInfo.value.username;
  basicForm.nickname = "";
  basicForm.gender = null;
  basicForm.phone = "";
  basicForm.email = "";
  basicFormRef.value.clearValidate();
};
</script>

<style scoped>
.profile-container {
  padding: 20px;
  background-color: #f5f5f5;
  display: flex; /* 确保子元素可以使用 Flexbox */
  flex-direction: column; /* 垂直方向的 Flexbox */
  height: 100%; /* 确保容器高度占满整个父容器 */
}

.profile-card,
.edit-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  background-color: #fff;
  padding: 20px;
  height: 100%; /* 确保卡片高度占满整个父容器 */
  flex: 1; /* 使卡片在垂直方向上伸展以匹配容器高度 */
  display: flex; /* 确保子元素可以使用 Flexbox */
  flex-direction: column; /* 垂直方向的 Flexbox */
}

.username {
  font-size: 25px;
  font-weight: bold;
  font-family: "仿宋";
  margin: 10px 0;
  color: #333;
}

.info-list {
  margin-top: 10px;
  text-align: left;
}

.info-item {
  margin: 15px 0;
  font-size: 16px;
}

.info-item .label {
  color: #606266;
  font-weight: 500;
  width: 80px;
  text-align: justify;
  display: inline-block;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0px 20px;
}

.avatar-uploader {
  text-align: center;
  margin-bottom: 20px;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 2px solid #dcdfe6;
}

.avatar-uploader-icon {
  width: 100px;
  height: 100px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
  border-radius: 50%;
  border: 2px dashed #dcdfe6;
  line-height: 100px;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.el-row {
  display: flex;
  align-items: stretch; /* 使子元素在垂直方向上拉伸以匹配容器高度 */
  flex: 1; /* 使行在垂直方向上伸展以匹配容器高度 */
}

.el-col {
  height: 100%; /* 确保列的高度占满整个父容器 */
}

.button-container {
  margin-top: auto; /* 将按钮容器推到卡片底部 */
  padding: 20px 0;
}
</style>
